package hbec.kettle.etl.plugins.core;

import java.util.Map;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.trans.Trans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import hbec.kettle.etl.common.exception.ExceptionTracker;
import hbec.kettle.etl.common.plugin.Result;
import hbec.kettle.etl.common.plugin.TransExecutable;

public class TransExecutor implements TransExecutable {
	private static final Logger logger = LoggerFactory.getLogger(TransExecutor.class);
	
	private Trans trans;
	private LogLevel logLevel;
	
	static {
		try {
			PluginEnvironment.init();
		} catch (KettleException e) {
			logger.error(ExceptionTracker.trace(e));
		}
	}

	@Override
	public void setTrans(Trans trans) {
		this.trans = trans;
	}
	
	@Override
	public void setVariables(Map<String, String> variables) {
		for (Map.Entry<String, String> var : variables.entrySet()) {
			trans.setVariable(var.getKey(), var.getValue());
		}
	}

	@Override
	public void setLogLevel(LogLevel logLevel) {
		this.logLevel = logLevel;
	}

	@Override
	public Result execute() {
		return execute(null);
	}
	
	@Override
	public Result execute(String[] args) {
		Result res = new Result();
		
        try {
        	// 设置转换日志等级
            trans.setLogLevel(logLevel);
            // 执行转换  
			trans.execute(args);
			// 等待转换执行结束  
	        trans.waitUntilFinished();
	        // 处理转换反馈信息
	        submitResult(trans, res);
		} catch (KettleException e) {
			logger.error(ExceptionTracker.trace(e));
		}
        
		return res;
	}
	
	private static void submitResult(Trans trans, Result res) {
		res.result = trans.getResult().getResult();
		
		res.entryNr = trans.getResult().getEntryNr();
		res.nrErrors = trans.getResult().getNrErrors();
		res.nrLinesInput = trans.getResult().getNrLinesInput();
		res.nrLinesOutput = trans.getResult().getNrLinesOutput();
		res.nrLinesUpdated = trans.getResult().getNrLinesUpdated();
		res.nrLinesRead = trans.getResult().getNrLinesRead();
		res.nrLinesWritten = trans.getResult().getNrLinesWritten();
		res.nrLinesDeleted = trans.getResult().getNrLinesDeleted();
		res.nrFilesRetrieved = trans.getResult().getNrFilesRetrieved();
		res.nrLinesRejected = trans.getResult().getNrLinesRejected();
		
		res.logChannelId = trans.getResult().getLogChannelId();
		res.logText = trans.getResult().getLogText();
		
		res.stopped = trans.getResult().stopped;
		res.exitStatus = trans.getResult().getExitStatus();
		//KettleLogStore.getAppender().getBuffer(trans.getLogChannelId(), false).toString();
	}
}
